package main

import (
	"context"
	"flag"
	"go-kit-starter/internal/server/grpc"
	"go-kit-starter/internal/tool"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/bilibili/kratos/pkg/naming"
	"github.com/bilibili/kratos/pkg/naming/discovery"

	"go-kit-starter/internal/server/http"
	"go-kit-starter/internal/service"

	"github.com/bilibili/kratos/pkg/conf/paladin"
	"github.com/bilibili/kratos/pkg/log"
)

func init() {


	//初始化配置文件
	flag.Parse()
	//初始化日志

	log.Init(&log.Config{
		Stdout:true,
		Dir:"./logger",
		MaxLogFile:1024,

	}) // debug flag: log.dir={path}
	defer log.Close()

	defaultConfPath := "../configs"
	isExist := tool.Exists(defaultConfPath)
	//存在配置文件目录
	if isExist {
		log.Info("debug模式找到configs目录  ")
		if client, err := paladin.NewFile(defaultConfPath); err == nil {
			paladin.DefaultClient = client
		} else {
			if err := paladin.Init(); err != nil {
				panic(err)
			}
		}
	} else {
		if err := paladin.Init(); err != nil {
			panic(err)
		}
	}

}

var ApplicationConfig *paladin.Map = new(paladin.Map)

func main() {

	log.Info("go-kit-starter start")

	//2 启动http和grpc服务
	svc := service.New()
	grpcSrv := grpc.New(svc)
	httpSrv := http.New(svc)
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)

	//3 热加载application.toml
	if err := paladin.Watch("application.toml", ApplicationConfig); err != nil {
		panic(err)
	}
	log.Info("ApplicationConfig,%+v", ApplicationConfig)
	var nodes []string = nil
	if err := ApplicationConfig.Get("nodes").Slice(&nodes); err != nil {
		log.Error("nodes不存在:", err)
		panic(err)
	}
	region, _ := ApplicationConfig.Get("region").String()
	zone, _ := ApplicationConfig.Get("zone").String()
	env, _ := ApplicationConfig.Get("env").String()
	appid, _ := ApplicationConfig.Get("appid").String()
	log.Info("env : %v", env)

	//4 注册服务发现
	conf := &discovery.Config{
		Nodes:  nodes,
		Region: region,
		Zone:   zone,
		Env:    env,
	}
	dis := discovery.New(conf)
	hn, _ := os.Hostname()
	ins := &naming.Instance{
		Zone:     zone,
		Env:      env,
		AppID:    appid,
		Hostname: hn,
		Addrs: []string{
			"http://" + http.BmConfig.Server.Addr,
			"grpc://" + grpc.WardenConfig.Server.Addr,
		},
	}
	cancelDis, err := dis.Register(context.Background(), ins)
	defer cancelDis()
	if err != nil {
		log.Info("注册服务发现失败~！")
		cancelDis()
		panic(err)
	}

	for {
		s := <-c
		log.Info("get a signal %s", s.String())
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
			if err := grpcSrv.Shutdown(ctx); err != nil {
				log.Error("grpcSrv Shutdown error(%v)", err)
			}
			if err := httpSrv.Shutdown(ctx); err != nil {
				log.Error("httpSrv.Shutdown error(%v)", err)
			}
			log.Info("kratos-demo exit")
			svc.Close()
			cancel()
			time.Sleep(time.Second)
			log.Info("kratos-demo exit over")
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}
